import * as path from "path";
import * as fs from "fs";
import * as ini from "ini";
import * as objectPath from "object-path";
import * as os from "os";

const filePath = path.resolve(__dirname, "./cfg.ini");
const fileHomePath = path.join(os.homedir(), ".xwidget.ini");

export class CfgStorage {
  cfg: any;

  private static inst: CfgStorage | null = null;

  static getInstance() {
    if (this.inst === null) {
      this.inst = new CfgStorage();
    }
    return this.inst;
  }

  constructor() {
    this.copy2home();
    this.cfg = ini.parse(fs.readFileSync(fileHomePath, "utf-8"));
  }

  copy2home() {
    if (!fs.existsSync(fileHomePath)) {
      fs.copyFileSync(filePath, fileHomePath);
    }
  }

  get<T>(keyPath: string) {
    return objectPath.get<T, T>(this.cfg, keyPath);
  }

  set(keyPath: string, v: any) {
    objectPath.set(this.cfg, keyPath, v);
    fs.writeFileSync(fileHomePath, ini.stringify(this.cfg));
  }
}
